package com.eyas.im.gui.swing.register;

import com.eyas.im.common.datasource.DataSourceUtils;
import com.eyas.im.gui.swing.common.CommonUtils;
import com.eyas.im.gui.swing.login.dao.IMUserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.sql.SQLException;
import java.util.regex.Pattern;

public class RegisterFrame extends JFrame implements ActionListener {
    private final static Logger logger = LoggerFactory.getLogger(RegisterFrame.class);
    private JTextField usernameField;
    private JPasswordField passwordField;
    private final static Pattern USERACCOUNT_PATTERN = Pattern.compile("^[a-zA-Z123456789][a-zA-Z0-9_]{8,20}$");
    public RegisterFrame() {
        this.initialFrame();
    }

    private void initialFrame() {
        this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        this.setResizable(false);
        this.addComponents();
        this.pack();
        Dimension screenSzie = Toolkit.getDefaultToolkit().getScreenSize();
        double x = screenSzie.getWidth();
        double y = screenSzie.getHeight();
        Dimension frameSize = this.getSize();
        double fx = frameSize.getWidth();
        double fy = frameSize.getHeight();
        this.setLocation((int)(x/2-fx/2),(int)(y/2-fy/2));
        this.setVisible(true);
    }

    private void addComponents() {
        JPanel mainPanel = new JPanel();
        GridBagLayout gridBagLayout = new GridBagLayout();
        mainPanel.setLayout(gridBagLayout);


        Font fontBlod20 = new Font("",Font.BOLD,20);
        JLabel usernameLable = new JLabel("账号:");
        usernameLable.setFont(fontBlod20);
        usernameField = new JTextField(20);
        usernameField.setFont(fontBlod20);

        JLabel passwordLable = new JLabel("密码:");
        passwordLable.setFont(fontBlod20);
        passwordField = new JPasswordField(20);
        passwordField.setFont(fontBlod20);

        JButton registerSubmit = new JButton("提交");
        registerSubmit.setActionCommand("regist");
        registerSubmit.setFont(fontBlod20);
        registerSubmit.addActionListener(this);
        JButton resetButton = new JButton("重置");
        resetButton.setActionCommand("reset");
        resetButton.addActionListener(this);
        resetButton.setFont(fontBlod20);


        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new Insets(10,5,5,10);
        mainPanel.add(usernameLable,gridBagConstraints);

        CommonUtils.resetGridBagConstraints(gridBagConstraints);
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new Insets(10,5,5,10);
        mainPanel.add(usernameField,gridBagConstraints);

        CommonUtils.resetGridBagConstraints(gridBagConstraints);
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new Insets(10,5,5,10);
        mainPanel.add(passwordLable,gridBagConstraints);

        CommonUtils.resetGridBagConstraints(gridBagConstraints);
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.insets = new Insets(10,5,5,10);
        mainPanel.add(passwordField,gridBagConstraints);

        CommonUtils.resetGridBagConstraints(gridBagConstraints);
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.insets = new Insets(10,5,5,10);
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(registerSubmit);
        buttonPanel.add(resetButton);
        mainPanel.add(buttonPanel,gridBagConstraints);

        this.add(mainPanel);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getActionCommand().equals("regist")) {
            logger.debug("注册按钮点击");
            String userAccount = this.usernameField.getText();
            String password = String.valueOf(this.passwordField.getPassword());
            if(!USERACCOUNT_PATTERN.matcher(userAccount).matches()) {
                JOptionPane.showMessageDialog(this,"[账号]的长度介于8~20，由字母、数字和下划线组成，且第一个字符不能是0和下划线");
                return;
            }
            if(password.length()<8||password.length()>20) {
                JOptionPane.showMessageDialog(this,"[密码]的长度介于8~20");
                return;
            }

            String result = this.saveUserAccount(userAccount,password);
            if(result!=null) {
                JOptionPane.showMessageDialog(this,result);
            }else {
                JOptionPane.showMessageDialog(this,"注册成功");
                this.dispose();
            }

        }else if(e.getActionCommand().equals("reset")) {
            logger.debug("注册信息重置按钮点击");
            this.usernameField.setText(null);
            this.passwordField.setText(null);
        }
    }

    /**
     *
     * @param userAccount
     * @param password
     * @return 返回NULL表示插入成功；否则返回失败信息
     */
    private String saveUserAccount(String userAccount,String password) {
        try {
            java.util.List<IMUserInfo> userinfos = DataSourceUtils.INSTANCE.query("select * from im_user_info where useraccount=? and validflag='1'",
                    IMUserInfo.class, userAccount);
            if(userinfos!=null&&userinfos.size()>0)
                return "账号已经被注册";
            DataSourceUtils.INSTANCE.execute("insert into im_user_info(useraccount,userpassword) values(?,?)",userAccount,password);
        } catch (Exception e) {
            logger.error("注册保存用户信息时，数据库出现问题",e);
            return e.getLocalizedMessage();
        }
        return null;
    }
}
